<?php

namespace app\api\controller;

use app\common\lib\Common;
use think\Controller;
use think\facade\App;
use \think\facade\Db;

class Evaluate extends Auth
{

    public function __construct()
    {
        parent::__construct();
        if ($this->role != 1) {
            $this->initreturn('越权操作');
        }
    }

    public function addEvaluate()
    {
        $post = input('post.');

        if (empty($post['orderid'])) {
            return $this->json([], 2000, '订单单参数错误');
        }

        $orderid = $post['orderid'];
        if (empty($post['score']) || !in_array($post['score'], [1, 2, 3, 4, 5])) {
            return $this->json([], 2000, '请选择评分');
        }

        $where = ['orderid' => $orderid];
        $info = $this->findTable('order', ['where' => $where]);

        if (empty($info)) {
            return $this->json([], 2000, '订单不存在，请刷新重试');
        }

        if ($info['memberid'] != $this->userid) {
            return $this->json([], 2000, '您无权限评价该订单');
        }

        if ($info['status'] != 6) {
            return $this->json([], 2000, '该订单未能评价');
        }

        $data = [
            'memberid' => $info['memberid'],
            'orderid' => $info['orderid'],
            'coachid' => $info['coachid'],
            'service' => empty($post['service']) ? '' : $post['service'],
            'score' => empty($post['score']) ? 5 : $post['score'],
            'evaluate' => empty($post['evaluate']) ? '' : $post['evaluate'],
            'imgs' => empty($post['imgs']) ? '' : (is_array($post['imgs']) ? $post['imgs'] : implode(',', $post['imgs'])),
        ];

        Db::startTrans();
        $ans = $this->insertTable('evaluate', $data);
        if (!$ans) {
            Db::rollback();
            return $this->json($post, 2000, '评价失败');
        }
        
        $update = [
            'where' => $where,
            'data' => ['status' => 7],
        ];

        $row = $this->updateTable('order', $update);
        if (!$row) {
            Db::rollback();
            return $this->json($post, 2000, '评价失败');
        }

        $time = date('Y-m-d H:i:s');
        $notice = [
            'type' => 2,
            'userid' => 0,
            'reciveutype' => 2,
            'reciveuid' => $info['coachid'],
            'reciveutable' => 'coach',
            'msgtitle' => "收到{$data['score']}分评价",
            'msgtext' => "您{$time}收到来自{$this->user['membertruename']}{$data['score']}分评价,赶紧去评价列表查看"
        ];
        $this->addnotice($notice);

        Db::commit();
        return $this->json($ans, 1001, '评价成功');
    }
}
